package com.springboot.controller;

import com.springboot.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private  String basepath;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info(file.toString());
        //获取原始文件名
        String fileName=file.getOriginalFilename();
        //获取文件后缀名
        String filenamemax = fileName.substring(fileName.lastIndexOf("."));
        //使用UUID重新生成文件名
        String newFileName= UUID.randomUUID().toString()+filenamemax;
        //判断文件是否存在
        File file1=new File(basepath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(basepath+newFileName));  //上传到指定目录
        }catch (IOException ex){
            ex.printStackTrace();
        }

        return R.success(newFileName);
    }

    //下载文件
    @GetMapping("/download")
   public void  download(String name, HttpServletResponse response){
        //输入流写入数据
   try {
       FileInputStream inputStream=new FileInputStream(new File(basepath+name));
       //输出流响应下载写入浏览器中
       ServletOutputStream servletOutputStream=response.getOutputStream();
       response.setContentType("image/jpeg");
        byte[]  buffer=new byte[1024];
        int len=0;
        while ((len=inputStream.read(buffer))!=-1){
            servletOutputStream.write(buffer,0,len);
            servletOutputStream.flush();
        }
   }catch (IOException exception){
       exception.printStackTrace();
   }
    }

}
